package com.cr.front.news.service.es;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import java.io.IOException;


// 定义一个用于初始化Elasticsearch索引的服务类
@Service
@Slf4j
public class ElasticSearchInitializer {


    // 定义一个Elasticsearch的高级客户端实例
    private RestHighLevelClient client;

    // 构造函数，在服务初始化时调用
    public ElasticSearchInitializer() {
        initClient(); // 初始化Elasticsearch客户端
    }

    // 初始化Elasticsearch客户端的方法
    private void initClient() {
        HttpHost host=new HttpHost("localhost",9200,"http");
        RestClientBuilder builder = RestClient.builder(host);
        client=new RestHighLevelClient(builder);
    }

    // 如果索引不存在则创建索引的方法
    public void createIndexIfNotExists() throws IOException {
        // 检查索引是否存在
        boolean exists = client.indices().exists(new GetIndexRequest("news"), RequestOptions.DEFAULT);
        if (exists) {
            //如果索引存在，则删除重新创建
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("news");
            client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            log.info("ES: 索引 'news' 已删除，准备重新创建.");
        }
        // 创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("news");

        // 定义索引的设置
        Settings.Builder setting =
                Settings.builder()
                        .put("number_of_shards", 1)
                        .put("number_of_replicas", 0);

        request.settings(setting);

        // 定义映射
        String mapping = "{\"properties\":{\"title\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"},\"categoryId\":{\"type\":\"text\"},\"status\":{\"type\":\"text\"},\"brief\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"},\"content\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"}}}";
        request.mapping(mapping, XContentType.JSON);

        // 执行创建索引请求
        client.indices().create(request, RequestOptions.DEFAULT);

    }

    // 关闭Elasticsearch客户端的方法
    public void closeClient() throws IOException {
        if (client != null) {
            client.close(); // 关闭客户端
        }
    }
}